package com.example.zx.theline.jclr;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.example.zx.theline.BodyActivity;
import com.example.zx.theline.R;
import com.example.zx.theline.jclr.pub.JcxxChaKanActivity;
import com.example.zx.theline.jclr.pub.ZsrjhtxjdjcActivity;
import com.loopj.android.http.RequestParams;
import com.scu.miomin.shswiperefresh.core.SHSwipeRefreshLayout;
import com.scu.miomin.shswiperefresh.view.SHListView;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import GsonBean.CheckInfoBean;
import GsonBean.JdjcdclBean;
import Utils.BackHandlerHelper;
import Utils.DateUtil;
import Utils.StatusUtil;
import app.MyApplication;
import base.BaseFragment;
import bean.CheckSearchBean;
import dialog.ZsrjhChaKanDialog;
import network.BaseCallBack;
import network.NetWorkApi;
import network.ObjectHttpResponseHandler;
import Utils.MyToast;
import Utils.NoDoubleClickUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import views.CheckSearchView;
import views.CheckSearchViewLr;

/**
 * Created by zx on 2017/4/14.
 */

public class CustodyListYclFragment extends BaseFragment {
    private SHSwipeRefreshLayout swipeRefreshLayout;
    private SHListView mListView;
    private TextView mFootTextView;

    //分页数据 正常信息
    int pageNumber = 0;
    int pageSize = 10;

    List<JdjcdclBean.RowsBean> mSoureList;

    MyAdapter mMyAdapter;

    ZsrjhChaKanDialog mZsrjhChaKanDialog;


    //是否第一次加载
    boolean isFirst = true;

    JdjcdclBean mJdjcdclBean;


    private TextView leftTextView,prev,centerTextView, next,rightTextView;

    CheckSearchViewLr mCheckSearchView;
    CheckSearchBean mCheckSearchBean;

    //标记fragment onstart时是否需要刷新
    public static boolean onStartRefresh = false;

    @Override
    protected void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
        InitData();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (onStartRefresh) {
            RefreshAllDate(1, 10);
            onStartRefresh = false;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_custody_list, null);

        mListView = (SHListView) view.findViewById(R.id.listview);
        //swipeRefreshLayout 下拉是刷新 上滑加载layout
        swipeRefreshLayout = (SHSwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        //swipeRefreshLayout footview
        View FootView = inflater.inflate(R.layout.refresh_view, null);
        mFootTextView = (TextView) FootView.findViewById(R.id.title);
        swipeRefreshLayout.setFooterView(FootView);

        leftTextView = (TextView) view.findViewById(R.id.leftTextView);
        prev = (TextView) view.findViewById(R.id.prev);
        next = (TextView) view.findViewById(R.id.next);
        rightTextView = (TextView) view.findViewById(R.id.rightTextView);
        centerTextView = (TextView) view.findViewById(R.id.centerTextView);


        mCheckSearchView = (CheckSearchViewLr) view.findViewById(R.id.checksearchview);
        mCheckSearchView.hideSfcs();
        InitView();
        InitSearchView();
        InitListen();
        return view;
    }


    public void InitView() {
    }

    @Override
    protected void InitData() {
        mSoureList = new ArrayList<>();
        mMyAdapter = new MyAdapter();
        mListView.setAdapter(mMyAdapter);
        mCheckSearchBean = new CheckSearchBean();
        centerTextView.setText(DateUtil.getYearAndMonthAndDay(date));

        mCheckSearchBean = new CheckSearchBean();
        //初始化搜索条件，搜索日期为当天
        setSearchBean();
        LoadMoreDate();
    }
    private void InitSearchView() {

        prev.setText("上一日");
        next.setText("下一日");
        centerTextView.setText(DateUtil.getYearAndMonthAndDay(date));

        mCheckSearchView.setConfirmListener(new CheckSearchViewLr.OnClick() {
            @Override
            public void onConfirmListener(CheckSearchBean Util) {
                mCheckSearchBean = Util;
                swipeRefreshLayout.startRefresh();
                RefreshAllDate(1, 10);
            }
        });
    }

    //按钮上一天事件
    public void butPrev() {
        date = DateUtil.getAfterDayDate(date, -1);
        setSearchBean();
        upDatedAndRefresh();
    }

    //按钮下一天事件
    public void butNext() {
        date = DateUtil.getAfterDayDate(date, 1);
        setSearchBean();
        upDatedAndRefresh();
    }
    //更新标题栏日期并刷新列表数据
    public void upDatedAndRefresh() {
        centerTextView.setText(DateUtil.getYearAndMonthAndDay(date));
        //刷新列表数据
        onRefresh();
    }

    //设置搜索日期
    private void setSearchBean() {
        mCheckSearchBean.setSgrq(DateUtil.getYearAndMonthAndDay(date));
    }


    public void onRefresh() {
        RefreshAllDate(1, 10); //刷新数据
    }


    @Override
    public boolean onBackPressed() {
        if (mCheckSearchView.getVisibility() == View.VISIBLE) {
            mCheckSearchView.setVisibility(View.GONE);
            return true;
        } else {
            return BackHandlerHelper.handleBackPress(this);
        }
    }

    @Override
    protected void InitListen() {
        prev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                butPrev();
            }
        });

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                butNext();
            }
        });

        centerTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView.getInstance(getContext(),CustodyListYclFragment.this.date,new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        CustodyListYclFragment.this.date=date;
                        setSearchBean();
                        upDatedAndRefresh();
                        RefreshAllDate(1, 10);
                    }
                }).show();
            }
        });

        leftTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BodyActivity.startThis(getActivity());
            }
        });

        mCheckSearchView.setConfirmListener(new CheckSearchViewLr.OnClick() {
            @Override
            public void onConfirmListener(CheckSearchBean Util) {
                mCheckSearchBean = Util;
                swipeRefreshLayout.startRefresh();
                RefreshAllDate(1, 10);
            }
        });
        rightTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mCheckSearchView.getVisibility() == View.GONE) {
                    mCheckSearchView.setVisibility(View.VISIBLE);
                    mCheckSearchView.setDefaultDate(mCheckSearchBean);
                }
            }
        });


        swipeRefreshLayout.setOnRefreshListener(new SHSwipeRefreshLayout.SHSOnRefreshListener() {

            //下滑刷新 完成
            @Override
            public void onRefresh() {
                //下滑更新ListView内所有数据
                RefreshAllDate(1, 10);

            }

            //上拉加载 完成
            @Override
            public void onLoading() {
                //加载更多数据
                LoadMoreDate();

            }

            /**
             * 监听下拉刷新过程中的状态改变
             * @param percent 当前下拉距离的百分比（0-1）
             * @param state 分三种状态{NOT_OVER_TRIGGER_POINT：还未到触发下拉刷新的距离；OVER_TRIGGER_POINT：已经到触发下拉刷新的距离；START：正在下拉刷新}
             */

            //下滑 刷新数据
            @Override
            public void onRefreshPulStateChange(float percent, int state) {
                switch (state) {
                    case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                        swipeRefreshLayout.setRefreshViewText("下拉刷新");

                        break;
                    case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                        swipeRefreshLayout.setRefreshViewText("松开刷新");

                        break;
                    case SHSwipeRefreshLayout.START:
                        swipeRefreshLayout.setRefreshViewText("正在刷新");

                        break;
                }
            }

            //上拉 加载更多数据
            @Override
            public void onLoadmorePullStateChange(float percent, int state) {
                switch (state) {
                    case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                        mFootTextView.setText("上拉加载");
                        break;
                    case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                        mFootTextView.setText("松开加载");
                        break;
                    case SHSwipeRefreshLayout.START:
                        mFootTextView.setText("正在加载...");
                        break;
                }
            }
        });

    }


    //获取监督检查待处理列表数据 传入
    private void LoadMoreDate() {
        pageNumber++;
        Map<String, String> map = new HashMap<>();
        map.put("pageNumber", String.valueOf(pageNumber));
        map.put("pageSize", String.valueOf(pageSize));
        map.put("loginId", MyApplication.getmLoginUser().getUserDisplayName());
        map.put("loginDwId", MyApplication.getmLoginUser().getUserUnitId());
        //搜索条件跟上滑加载结合  搜索条件
        map = setMap(map, mCheckSearchBean);
        MyApplication.ShowWaitDialog(getContext());
        NetWorkApi.getCustodyYclData(map, new BaseCallBack<JdjcdclBean>() {

                    @Override
                    public void Success(Call<JdjcdclBean> call, Response<JdjcdclBean> response) {
                        try {
                            mJdjcdclBean = response.body();
                            if (mJdjcdclBean.getMsg().equals("success")) {
                                mSoureList.addAll(mJdjcdclBean.getRows());
                                mMyAdapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void Failure(Call<JdjcdclBean> call, Throwable t) {
                        MyToast.showFail();
                    }

                    @Override
                    public void onFinally() {
                        swipeRefreshLayout.finishLoadmore();
                    }
                }
        );

    }

    //一条数据更新以后 更新数据
    private void RefreshAllDate(int PageNumber, int PageSize) {
        this.pageNumber = PageNumber;
        Map<String, String> map = new HashMap<>();
        map.put("pageNumber", String.valueOf(PageNumber));
        map.put("pageSize", String.valueOf(PageSize));
        map.put("loginId", MyApplication.getmLoginUser().getUserDisplayName());
        map.put("loginDwId", MyApplication.getmLoginUser().getUserUnitId());
        //搜索条件跟上滑加载结合  搜索条件
        map = setMap(map, mCheckSearchBean);
        MyApplication.ShowWaitDialog(getContext());
        NetWorkApi.getCustodyYclData(map, new BaseCallBack<JdjcdclBean>() {

                    @Override
                    public void Success(Call<JdjcdclBean> call, Response<JdjcdclBean> response) {
                        try {
                            JdjcdclBean mJdjcdclBean = response.body();
                            if (mJdjcdclBean.getMsg().equals("success")) {
                                mSoureList = mJdjcdclBean.getRows();
                                mListView.setAdapter(mMyAdapter);
                            }
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void Failure(Call<JdjcdclBean> call, Throwable t) {
                        MyToast.showFail();

                    }

                    @Override
                    public void onFinally() {
                        swipeRefreshLayout.finishRefresh();
                    }
                }

        );
    }


    //点击每一条信息的计划号以后根据点击的计划号获取计划号数据并显示
    public void getCheckInfoData(String bh) {
        MyApplication.ShowWaitDialog(getContext());
        NetWorkApi.getCheckInfoData(bh, new Callback<CheckInfoBean>() {
                    @Override
                    public void onResponse(Call<CheckInfoBean> call, Response<CheckInfoBean> response) {
                        try {
                            CheckInfoBean mCheckInfoBean = response.body();
                            showCheckPlanDialog(mCheckInfoBean);
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void onFailure(Call<CheckInfoBean> call, Throwable t) {
                        MyToast.showFail();

                    }
                }
        );
    }

    //显示计划详情diaog
    public void showCheckPlanDialog(CheckInfoBean mCheckInfoBean) {
        mZsrjhChaKanDialog = new ZsrjhChaKanDialog(getContext(), mCheckInfoBean);
        mZsrjhChaKanDialog.show();
    }

    //显示dialog  检查信息编辑 dialog
    public void goToJcxxChakanActivity(int Position) {
        Intent mIntent = new Intent(getActivity(), JcxxChaKanActivity.class);
        Bundle mBundle = new Bundle();
        //日监督计划编号
        mBundle.putString("rjdjhbBh", mSoureList.get(Position).getBh());
        //监督检查表编号
        mBundle.putString("jdjhjcbId", mSoureList.get(Position).getJdjhjcbId());
        mIntent.putExtras(mBundle);
        startActivity(mIntent);
    }


    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mSoureList.size();
        }

        @Override
        public Object getItem(int position) {
            return mSoureList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder mHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.ycl_custdylist_adapter, null);
                mHolder = new ViewHolder();
                mHolder.rjhh_layout = (LinearLayout) convertView.findViewById(R.id.rjhh_layout);
                mHolder.tablelayout = (LinearLayout) convertView.findViewById(R.id.tablelayout);
                mHolder.jhh = (TextView) convertView.findViewById(R.id.jhh);
                mHolder.sgrq = (TextView) convertView.findViewById(R.id.sgrq);
                mHolder.sglx = (TextView) convertView.findViewById(R.id.sglx);
                mHolder.sgdd = (TextView) convertView.findViewById(R.id.sgdd);
                mHolder.sgxm = (TextView) convertView.findViewById(R.id.sgxm);
                mHolder.ztpj = (TextView) convertView.findViewById(R.id.ztpj);
                mHolder.jcr = (TextView) convertView.findViewById(R.id.jcr);
                mHolder.jcsj = (TextView) convertView.findViewById(R.id.jcsj);
                mHolder.jcqk = (TextView) convertView.findViewById(R.id.jcqk);
                mHolder.zt = (TextView) convertView.findViewById(R.id.zt);
                mHolder.sfjytg = (ImageView) convertView.findViewById(R.id.sfjytg);
                mHolder.tgwz = (ImageView) convertView.findViewById(R.id.tgwz);
                mHolder.tgsq = (ImageView) convertView.findViewById(R.id.tgsq);
                convertView.setTag(mHolder);
            } else {
                mHolder = (ViewHolder) convertView.getTag();
            }

            //日计划号linearlayout设置click时间 查看该条日计划详情
            mHolder.rjhh_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!NoDoubleClickUtils.isDoubleClick())
                        getCheckInfoData(mSoureList.get(position).getBh());
                }
            });

            mHolder.jhh.setText("" + mSoureList.get(position).getBh() + "");
            mHolder.sgrq.setText("" + mSoureList.get(position).getExsgrq() + "");
            mHolder.sglx.setText(mSoureList.get(position).getLb() + "类");
            if (mSoureList.get(position).getLb().equals("B")) {
                mHolder.sglx.setTextColor(getResources().getColor(R.color.colorTextB));
            } else if (mSoureList.get(position).getLb().equals("C")) {
                mHolder.sglx.setTextColor(getResources().getColor(R.color.colorTextC));
            }

            mHolder.sgdd.setText("" + mSoureList.get(position).getSgdd() + "");
            mHolder.sgxm.setText("" + mSoureList.get(position).getXmmc() + "");
            mHolder.ztpj.setText("" + mSoureList.get(position).getZtpj() + "");
            mHolder.jcr.setText("" + mSoureList.get(position).getJcrName() + "");
            mHolder.jcsj.setText("" + mSoureList.get(position).getJcrq() + "");
            mHolder.jcqk.setText("" + mSoureList.get(position).getJcqk() + "");
            mHolder.zt.setText(StatusUtil.getStatusByInt(mSoureList.get(position).getJcbstatus()));

            mHolder.sfjytg.setVisibility(View.GONE);
            mHolder.tgwz.setVisibility(View.GONE);
            mHolder.tgsq.setVisibility(View.GONE);
            //状态为150 160 250 状态字段颜色为红色 其他状态为绿色
            if(mSoureList.get(position).getJcbstatus()==150
                    ||mSoureList.get(position).getJcbstatus()==160
                    ||mSoureList.get(position).getJcbstatus()==250)
            {
                mHolder.zt.setTextColor(getContext().getResources().getColor(R.color.colorRed));
            } else {
                mHolder.zt.setTextColor(getContext().getResources().getColor(R.color.colorGreenTitle));
            }

            //停工项目 状态标记为120 130 状态 为停工申请
            if (mSoureList.get(position).getSfjytg() != null && mSoureList.get(position).getSfjytg().equals("1") && (mSoureList.get(position).getJcbstatus() == 120 || mSoureList.get(position).getJcbstatus() == 130)) {
                mHolder.tgsq.setVisibility(View.VISIBLE);
            } else {
                mHolder.tgsq.setVisibility(View.GONE);
            }

            //停工项目 状态标记大于 130 且不等于 150 160 状态 停工图标显示
            if (mSoureList.get(position).getSfjytg() != null && mSoureList.get(position).getSfjytg().equals("1") && mSoureList.get(position).getJcbstatus() > 130 && (mSoureList.get(position).getJcbstatus() != 150 && mSoureList.get(position).getJcbstatus() != 160)) {
                mHolder.sfjytg.setVisibility(View.VISIBLE);
            } else {
                mHolder.sfjytg.setVisibility(View.GONE);
            }

            //停工项目 状态标记大于 130 且等于 150或160 状态 停工图标显示
            if (mSoureList.get(position).getSfjytg() != null && mSoureList.get(position).getSfjytg().equals("1") && (mSoureList.get(position).getJcbstatus() == 150 || mSoureList.get(position).getJcbstatus() == 160)) {
                mHolder.tgwz.setVisibility(View.VISIBLE);
            } else {
                mHolder.tgwz.setVisibility(View.GONE);
            }

            mHolder.tablelayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    goToJcxxChakanActivity(position);
                }
            });
            return convertView;
        }

        class ViewHolder {

            //日计划号
            LinearLayout rjhh_layout;

            //查看详情 点击区域扩大
            LinearLayout tablelayout;

            //施工计划
            TextView jhh;

            //施工日期
            TextView sgrq;

            //施工类型
            TextView sglx;

            //施工地点
            TextView sgdd;

            //施工项目
            TextView sgxm;

            //总体评价
            TextView ztpj;

            //检查人
            TextView jcr;

            //检查时间
            TextView jcsj;

            //检查情况
            TextView jcqk;

            //状态
            TextView zt;

            ImageView sfjytg;

            //停工未准
            ImageView tgwz;

            //停工申请
            ImageView tgsq;

        }

    }

    public Map<String, String> setMap(Map<String, String> map, CheckSearchBean Bean) {
        if (Bean != null) {
            if (Bean.getSgrq() != null && !Bean.getSgrq().equals("")) {
                map.put("searchDate", Bean.getSgrq());
            } else {
                map.put("searchDate", DateUtil.getCurDate());
            }
            if (Bean.getJcr() != null && !Bean.getJcr().equals("")) {
                map.put("seachJcrName", Bean.getJcr());
            }
            if (Bean.getXm() != null && !Bean.getXm().equals("")) {
                map.put("searchXlMc", Bean.getXm());
            }
            if (Bean.getDwhbm() != null) {
                map.put("searchDwId", Bean.getDwhbm().getLjyyxDwxxId());
            }
            if (Bean.getRjhh() != null) {
                map.put("searchBh", Bean.getRjhh());
            }
        }
        return map;
    }

//    //根据传入计划状态编号jcbstatus  获取状态中文
//    public String getJhzt(int status) {
//        String s;
//
//        switch (status) {
//            case 0:
//                s = "草稿";
//                break;
//            case 14:
//                s = "草稿";
//                break;
//            case 30:
//                s = "已完成";
//                break;
//            case 40:
//                s = "已完成";
//                break;
//            default:
//                s = "处理中";
//                break;
//        }
//        return s;
//    }
}
